#include "mainwidget.h"
#include "ui_mainwidget.h"
#include "qimageprocessing.h"

MainWidget::MainWidget(int viewnb, int h, int w, QWidget *parent) :
    QWidget(parent), m_capt_height(h),m_capt_width(w),

    ui(new Ui::MainWidget)
{
    ui->setupUi(this);
    connect(&m_timer,SIGNAL(timeout()),this,SLOT(refresh()));
    connect(ui->bUpdate,SIGNAL(released()),this,SLOT(refresh()));
    connect(ui->bFindGrid,SIGNAL(released()),this,SLOT(findGrid()));
    connect(ui->cLectCont,SIGNAL(toggled(bool)),this,SLOT(checkBox(bool)));
    connect(QImageProcessing::instance(),SIGNAL(envoi_txt(QString)),ui->textBrowser,SLOT(append(QString)));

    m_capWebcam = new cv::VideoCapture();
    m_capWebcam->open(0);

    m_capWebcam->set(CV_CAP_PROP_FRAME_WIDTH, m_capt_width);
    m_capWebcam->set(CV_CAP_PROP_FRAME_HEIGHT, m_capt_height);

    cv::Mat image(m_capt_height, m_capt_width, CV_8UC3, cv::Scalar(0,0,0));
    for(int i=0;i<viewnb;i++) {
        m_cvImage << new QCVImageWidget(this);
        ui->layouthaut->addWidget(m_cvImage[i],i%2,i/2);
        m_cvImage[i]->showImage(image);
    }

    m_timer.start(40);
}

MainWidget::~MainWidget()
{

    for(int i=0;i<m_cvImage.size();i++)
        delete m_cvImage[i];

    m_capWebcam->release();
    delete ui;
}


void MainWidget::checkBox(bool state)
{
    if(state == false)
        m_timer.stop();
    else
        m_timer.start(40);
}

void MainWidget::findGrid()
{
    ui->textBrowser->append(QString("Capture " ));

    cv::Mat image;
    m_capWebcam->read(image);
    QImageProcessing::instance()->traitementimage(image);
    if(m_cvImage.size()<2)
        ui->textBrowser->append(QString("Pas assez d'écran" ));
    else
        m_cvImage[1]->showImage(image);


}

void MainWidget::refresh()
{
    cv::Mat image;
    m_capWebcam->read(image);

    if(m_cvImage.size()!=0)
        m_cvImage[0]->showImage(image);

    QImageProcessing::instance()->sortLinesHori(0,0);
}

